package com.visionblue.business.ship.page.collection.record

import android.content.Context
import android.view.View
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.core.widget.doOnTextChanged
import com.visionblue.business.ship.R
import com.visionblue.business.ship.model.enums.RecordMode
import com.visionblue.business.ship.model.enums.WasteTypeEnum
import com.visionblue.business.ship.model.repository.db.CollectionRecord
import com.visionblue.business.ship.page.dialog.SelectionDialog
import com.visionblue.business.ship.page.dialog.SelectionItem
import com.visionblue.business.ship.util.FormatUtils
import com.visionblue.business.ship.view.AddSubTextView
import com.visionblue.business.ship.view.refresh.BaseHolder
import com.visionblue.business.ship.view.refresh.StatusAdapter
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.item_collection_record.*
import kotlinx.android.synthetic.main.view_add_sub.view.*
import java.math.BigDecimal

/**
 * @author: xlh
 * @date: 2020-05-20 7:10 PM
 * @desc:
 */
class RecordAdapter : StatusAdapter<CollectionRecord>() {

    var mode: RecordMode = RecordMode.TEXT_MODE

    var mOnViewClickListener: OnViewClickListener? = null


    override fun getHolder(v: View?, viewType: Int): BaseHolder<CollectionRecord> {
        return VH(v)
    }

    override fun getLayoutId(viewType: Int): Int {
        return R.layout.item_collection_record
    }

    fun remove(rmData: CollectionRecord?) {
        if (infos.remove(rmData)) {
            notifyDataSetChanged()
        }
    }

//    fun setMenuItems(menuItems: List<MeasureMenuItem>) {
//
//    }

    inner class VH(override val containerView: View?) : BaseHolder<CollectionRecord>(containerView),
        LayoutContainer {
        override fun bindData(data: CollectionRecord?, position: Int) {
            val wasteTypeEnum = WasteTypeEnum.getWasteType(data?.wasteType)
            val typeText = if (wasteTypeEnum?.desc.isNullOrEmpty()) "请选择" else wasteTypeEnum?.desc
            tvWasteType.text =
                if (typeText!!.length > 5) FormatUtils.encrypt(typeText, 5) else typeText

/*            tvWeight.setUnit(
                if (wasteTypeEnum?.isSolid() == true) {
                    "kg"
                } else "m³"
            )*/
            tvWeight.setText(
                BigDecimal(
                    (if (data?.finalWeight != null) data.finalWeight.toString() else data?.originWeight.toString())
                )
            )

            //修改累计流量单位默认为m3
            if(data?.accumulationFlowUnit=="L"){
                tvWeightUnit.text = "m3"
            }else{
                tvWeightUnit.text = data?.accumulationFlowUnit
            }

            tvNo.text = "${itemCount - position}."

            tvStatus.visibility = View.GONE
            tvDuration.visibility = View.VISIBLE
            ivDelete.visibility = View.INVISIBLE

            ivDelete.setOnClickListener {
                remove(data)
                this@RecordAdapter.mOnViewClickListener?.onDeleteClick(data)
            }

    /*        if (wasteTypeEnum?.isSolid() == true) {
                tvWeight.setAddSubVal(BigDecimal.ONE)
            } else {
                tvWeight.setAddSubVal(BigDecimal("0.001"))
            }*/
            tvWeight.setAddSubVal(BigDecimal("0.001"))
            tvWasteType.setOnClickListener(null)
            tvWasteType.setBackgroundResource(R.drawable.bg_rectround_line_white_greyd7_5dp)
            tvWasteType.setTextColor(ContextCompat.getColor(itemView.context, R.color.black6))

            if (data?.startTime == data?.endTime) {
                tvDuration.text = FormatUtils.formatTimeHHmmss(data?.startTime)
            } else {
                if (data?.endTime != null) {
                    tvDuration.text =
                        "${FormatUtils.formatTimeHHmmss(data.startTime)}-${FormatUtils.formatTimeHHmmss(
                            data?.endTime
                        )}"
                }
            }

            // 废物种类可以修改
            tvWasteType.setOnClickListener {


                if (wasteTypeEnum == null) return@setOnClickListener
                when {
                    wasteTypeEnum.isOil() || wasteTypeEnum == WasteTypeEnum.OIL_UNDEFINE -> {
                        showFlowSelectionDialog(it.context, data, position)
                    }
                    wasteTypeEnum.isSolid() -> {
                        showSolidSelectionDialog(it.context, data, position)
                    }
                    wasteTypeEnum.isWater() || wasteTypeEnum == WasteTypeEnum.WATER_UNDEFINE ||wasteTypeEnum == WasteTypeEnum.WASTE_WATER_UNDEFINE-> {
                        showFlowSelectionDialog(it.context, data, position)
                    }
                    wasteTypeEnum == WasteTypeEnum.ULTRA_UNDEFINE -> {
                        showFlowSelectionDialog(it.context, data, position)
                    }
                }
            }

            val params = flWeight.layoutParams as LinearLayout.LayoutParams

            when (mode) {
                RecordMode.TEXT_MODE -> {
                    tvNo.visibility = View.VISIBLE
//                    changeTvWeightLeftMargin(0)
                    tvWeight.changeMode(AddSubTextView.TEXT_MODE)
                    ivDelete.visibility = View.INVISIBLE
                    val endTime = data?.endTime
                    if (endTime == null) {
                        tvDuration.visibility = View.GONE
                        tvStatus.visibility = View.VISIBLE
                        if (data?.alias.isNullOrEmpty()) {
                            tvStatus.animateText("计量中...")
                        } else {
                            tvStatus.animateText("${data?.alias}计量中...")
                        }
                    } else {
                        tvDuration.visibility = View.VISIBLE
                    }

                    params.weight = 1f
//                    if (wasteTypeEnum?.desc.isNullOrEmpty()) {
//                        tvWasteType.setOnClickListener {
//                            showOilSelectionDialog(it.context, data, position)
//                        }
//                    } else {
//                        tvWasteType.setOnClickListener(null)
//                    }
                }
                RecordMode.CHECK_MODE -> {
                    tvNo.visibility = View.GONE
//                    changeTvWeightLeftMargin(50)
                    tvWeight.changeMode(AddSubTextView.EDIT_MODE)
                    ivDelete.visibility = View.VISIBLE
                    tvStatus.visibility = View.GONE
//                    tvDuration.visibility = View.GONE
                    params.weight = 1.3f

                    tvWeight.etInput.doOnTextChanged { _, _, _, _ ->
                        data?.finalWeight =
                            FormatUtils.format3Decimal(tvWeight.getVal()?.toDouble())
                                .toFloatOrNull()
                    }

//                    if (wasteTypeEnum?.isSolid() == true) {
//                        tvWasteType.setTextColor(
//                            ContextCompat.getColor(
//                                itemView.context,
//                                R.color.greyb5
//                            )
//                        )
//                        tvWasteType.setBackgroundResource(R.drawable.bg_rectround_line_greyb5_5dp)
//                    } else {
                    tvWasteType.setTextColor(
                        ContextCompat.getColor(
                            itemView.context,
                            R.color.black6
                        )
                    )
                    tvWasteType.setBackgroundResource(R.drawable.bg_rectround_line_white_greyd7_5dp)
//                    }
                }
            }

            flWeight.layoutParams = params
        }

        private fun showSolidSelectionDialog(
            context: Context,
            data: CollectionRecord?,
            position: Int
        ) {
            SelectionDialog(
                context, listOf(
                    // 生活垃圾
                    SelectionItem(WasteTypeEnum.SOLID_WASTE.desc, {

                       val isOk: Boolean? =   this@RecordAdapter.mOnViewClickListener?.onWasteTypeSelectionClick(data,WasteTypeEnum.SOLID_WASTE.code)
                        if (isOk!!){
                            data?.wasteType = WasteTypeEnum.SOLID_WASTE.code
                            notifyDataSetChanged()
                        }
                    })

                  /*  ,
                    // 油包
                    SelectionItem(WasteTypeEnum.OIL_PACKAGE.desc, {
                        data?.wasteType = WasteTypeEnum.OIL_PACKAGE.code
                        this@RecordAdapter.mOnViewClickListener?.onWasteTypeSelectionClick(data)
                        notifyItemChanged(position)
                    }),
                    // 废铅酸电池
                    SelectionItem(WasteTypeEnum.WASTE_LEAD_ACID_BATTERY.desc, {
                        data?.wasteType = WasteTypeEnum.WASTE_LEAD_ACID_BATTERY.code
                        this@RecordAdapter.mOnViewClickListener?.onWasteTypeSelectionClick(data)
                        notifyItemChanged(position)
                    })*/
                )
            ).show()
        }

        private fun showFlowSelectionDialog(
            context: Context,
            data: CollectionRecord?,
            position: Int
        ) {
            SelectionDialog(
                context, listOf(
                    // 生活污水
                    SelectionItem(WasteTypeEnum.LIFE_WASTE.desc, {

                       val isOk = this@RecordAdapter.mOnViewClickListener?.onWasteTypeSelectionClick(data,WasteTypeEnum.LIFE_WASTE.code)
                        if (isOk!!){
                            data?.wasteType = WasteTypeEnum.LIFE_WASTE.code
                            notifyDataSetChanged()
                        }

                    }),
        /*            // 含有毒液体物质的污水
                    SelectionItem(WasteTypeEnum.HAZARDOUS_WASTE.desc, {
                        data?.wasteType = WasteTypeEnum.HAZARDOUS_WASTE.code
                        this@RecordAdapter.mOnViewClickListener?.onWasteTypeSelectionClick(data)
                        notifyItemChanged(position)
                    }),*/
                    // 含油污水
                    SelectionItem(WasteTypeEnum.OIL_WASTE.desc, {

                       val isOk = this@RecordAdapter.mOnViewClickListener?.onWasteTypeSelectionClick(data,WasteTypeEnum.OIL_WASTE.code)
                        if (isOk!!){
                            data?.wasteType = WasteTypeEnum.OIL_WASTE.code
                            notifyItemChanged(position)
                        }
                    }),
                    // 残油
                    SelectionItem(WasteTypeEnum.RESIDUAL_OIL.desc, {

                        val isOk =   this@RecordAdapter.mOnViewClickListener?.onWasteTypeSelectionClick(data,WasteTypeEnum.RESIDUAL_OIL.code)
                        if (isOk!!){
                            data?.wasteType = WasteTypeEnum.RESIDUAL_OIL.code
                            notifyDataSetChanged()
                        }
                    })
                )
            ).show()
        }

//        private fun showOilSelectionDialog(
//            context: Context,
//            data: CollectionRecord?,
//            position: Int
//        ) {
//            SelectionDialog(
//                context, listOf(
//
//                )
//            ).show()
//        }


//        private fun changeTvWeightLeftMargin(leftMargin: Int) {
//            val params = tvWeight.layoutParams as FrameLayout.LayoutParams
//            params.leftMargin = DeviceUtil.dip2px(containerView?.context, leftMargin.toFloat())
//            tvWeight.layoutParams = params
//        }
    }

    interface OnViewClickListener {
        fun onDeleteClick(record: CollectionRecord?)
        fun onWasteTypeSelectionClick(record: CollectionRecord?,type:String):Boolean

    }

}